greedy implementation sortings *900

Please click on ads to support us..

Python Code:

n = int(input())
arr = list(map(int, input().split()))
arr.sort(reverse=True)
a = list(filter(lambda x: x % 2, arr))
b = list(filter(lambda x: not x % 2, arr))
s = sum(arr)
k = min(len(a), len(b))
for i in range(k):
    s -= a[i] + b[i]
if len(a) > len(b):
    s -= a[k]
elif len(b) > len(a):
    s -= b[k]
print(s)

C++ Code:

#include<bits/stdc++.h>

#define ll long long

#define ld long double

#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)



using namespace std;



int main ()

{

	fast;

	

	vector<int> v1;

	vector<int> v2;

	

	int n;

	cin>>n;

	int a;

	

	while ( n-- )

	{

		cin>>a;

		if ( a % 2 == 0 )

		{

			v1.push_back(a);

		}

		else {

			v2.push_back(a);

		}

	}

	int x = v1.size();

	int y = v2.size();

	

	if ( abs ( x - y ) <= 1 )

	{

		cout<<0<<endl;

		return 0;

	}

	else {

	sort ( v1.begin(), v1.end() );

	sort ( v2.begin(), v2.end() ); 

	int s = 0;

	if ( x > y )

	{

		for ( int i = 0; i < abs ( x - y ) - 1; i++ )

		{

			s += v1[i];

		}

	}

	else

	{

		for ( int j = 0; j < abs ( x - y ) - 1; j++ )

		{

			s += v2[j];

		}

	}

	cout<<s<<endl;

	}

	return 0;

}


Comments

Submit
0 Comments
More Questions

1480A - Yet Another String Game
1216C - White Sheet
1648A - Weird Sum
427A - Police Recruits
535A - Tavas and Nafas
581A - Vasya the Hipster
1537B - Bad Boy
1406B - Maximum Product
507B - Amr and Pins
379A - New Year Candles
1154A - Restoring Three Numbers
750A - New Year and Hurry
705A - Hulk
492B - Vanya and Lanterns
1374C - Move Brackets
1476A - K-divisible Sum
1333A - Little Artem
432D - Prefixes and Suffixes
486A - Calculating Function
1373B - 01 Game
1187A - Stickers and Toys
313B - Ilya and Queries
579A - Raising Bacteria
723A - The New Year Meeting Friends
302A - Eugeny and Array
1638B - Odd Swap Sort
1370C - Number Game
1206B - Make Product Equal One
131A - cAPS lOCK
1635A - Min Or Sum